import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:du_application/conpoments/bottomBar.dart';
import 'package:du_application/model/AffairListModel.dart';
import 'package:du_application/provide/AffairListProvider.dart';
import 'package:du_application/routes/application.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:provide/provide.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
class AffairList extends StatefulWidget {
AffairList({Key key}) : super(key: key);

_AffairListState createState() => _AffairListState();
  
  }
  class _AffairListState extends State<AffairList>{
   ScrollController controller=ScrollController();
       RefreshController _refreshController =RefreshController(initialRefresh: true);
       Widget build(BuildContext context) {
     
     void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }
   void _onLoading(AffairListModel affairListModel) async {

     int page=affairListModel.data.page+1;
       print(page>affairListModel.data.pages);
    if(page>affairListModel.data.pages){
    
         setState(() {
             _refreshController.loadNoData();
        });
     
    return;
      }
   try{
      Timer t = Timer(Duration(seconds: 10000), () {
           setState(() {
              _refreshController.loadFailed();
        });
     
  
    });
     AffairListModel aaffairListModel= await Provide.value<AffairListProvider>(context).getAffair(context,page,affairListModel.data.limit);
    if(aaffairListModel.errno==0){
     t.cancel();
     _refreshController.loadComplete();
    }
   }catch(e){
         setState(() {
              _refreshController.loadFailed();
        });
   }
  }

    return  Provide<AffairListProvider>(
      builder:(context,child,provide){
         return provide==null||provide.affairListModel==null?Scaffold(): Scaffold(
      // appBar: AppBar(),
     bottomNavigationBar: BottomBar(),
      body:  SmartRefresher(
        enablePullDown: false,
        enablePullUp: true,
        header: ClassicHeader(
         releaseText: '松开手刷新',
         refreshingText: '刷新中',
         completeText: '刷新完成',
         failedText: '刷新失败',
         idleText: '下拉刷新',
        ),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = Text("下拉加载");
            }
            else if (mode == LoadStatus.loading) {
              body = CupertinoActivityIndicator();
            }
            else if (mode == LoadStatus.failed) {
              body = Text("请求失败,请重试");
            }
            else {
              body = Text("没有数据啦");
            }
            return Container(
              height: 55.0,
              child: Center(child: body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: (){
          _onLoading(provide.affairListModel);
        },
       child:provide.affairs!=null&&provide.affairs.length>0? StaggeredGridView.countBuilder(
       controller: controller,
      shrinkWrap: true,
      padding: const EdgeInsets.all(8.0),
      crossAxisCount: 4,
      itemCount: provide.affairs.length,
      itemBuilder: (context, i) {
        String imgPath =provide.affairs[i].affair.url;
        return new Material(
          child: new InkWell(
            onTap: () {
            Application.router.navigateTo(context, "/affairDetail?id=${provide.affairs[i].affair.id}");
            },
            child: Column(
              children: <Widget>[
                Stack(
                  children: <Widget>[
                    Container(
                      child: Hero(
                        tag: i,
                        child: Stack(
                          alignment: Alignment.bottomCenter,
                          children: <Widget>[
                            CachedNetworkImage(
                              imageUrl: imgPath,
                              fit: BoxFit.cover,
                              placeholder: (context, url) =>
                                  Image.asset('assets/loading.jpg'),
                              // print("111");
                            ),
                            Container(
                              height: 50,
                              decoration: new BoxDecoration(
                                gradient: LinearGradient(
                                    begin: Alignment.bottomCenter,
                                    end: Alignment.topCenter,
                                    colors: [
                                      Color.fromRGBO(0, 0, 0, 0.5),
                                      // Color.fromRGBO(0, 0, 0, 0.5),
                                      Color.fromRGBO(0, 0, 0, 0)
                                    ]),
                              ),
                              //  color: Color.fromRGBO(0, 0, 0, 0.1),
                            )
                          ],
                        ),
                      ),
                    ),
                    Positioned(
                      bottom: ScreenUtil().setWidth(20),
                      left: ScreenUtil().setWidth(15),
                      child: Icon(
                        Icons.looks,
                        color: Colors.white,
                      ),
                    ),
                    Positioned(
                        bottom: ScreenUtil().setWidth(25),
                        left: ScreenUtil().setWidth(65),
                        child: Text(
                          "29",
                          style: TextStyle(color: Colors.white),
                        )),
                  ],
                ),
                Container(
                  margin:
                      EdgeInsets.symmetric(vertical: ScreenUtil().setSp(20)),
                  width: ScreenUtil().setWidth(500),
                  child: Text(
                    "${provide.affairs[i].affair.content}",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    textAlign: TextAlign.left,
                  ),
                ),
                Container(
                    margin: EdgeInsets.only(bottom: ScreenUtil().setSp(20)),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Container(
                              margin: EdgeInsets.symmetric(
                              horizontal: ScreenUtil().setSp(10)),
                              width: ScreenUtil().setWidth(50),
                              height: ScreenUtil().setWidth(50),
                              child: CircleAvatar(
                                backgroundImage: NetworkImage(
                                    "${provide.affairs[i].userInfo.avatarUrl}"),
                              ),
                            ),
                            Text(
                              "${provide.affairs[i].userInfo.nickName}",
                              style: TextStyle(color: Colors.grey[600]),
                            )
                          ],
                        ),
                      
                      ],
                    ))
              ],
            ),
          ),
        );
      },
      staggeredTileBuilder: (index) => new StaggeredTile.fit(2),
      mainAxisSpacing: 8.0,
      crossAxisSpacing: 8.0,
    ):Center(child:Text("没有数据~~~",style: TextStyle(
      color: Colors.black
    ),) ,)
   ,
    ));


      });  
  }


  }


